package com.flow.framework.schedule.job;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.flow.framework.cache.service.cache.common.ICommonCacheService;
import com.flow.framework.common.error.SystemErrorCode;
import com.flow.framework.common.exception.CheckedException;
import com.flow.framework.core.properties.FrameworkCoreConfigProperties;
import com.flow.framework.core.response.Response;
import com.flow.framework.core.util.ProxyUtil;
import com.flow.framework.facade.system.module.service.ISystemFrameworkModuleService;
import com.flow.framework.persistence.pojo.po.base.BaseSystemVersionPo;
import com.flow.framework.schedule.pojo.bo.ScheduleRequiredFieldBo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 调度base system version po分页处理任务抽象实现
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/4/10
 */
@Slf4j
public abstract class BaseSystemVersionScheduleJob<E extends BaseSystemVersionPo> extends BaseScheduleJob implements IPagePoScheduleHandler<E> {

    private final ScheduleRequiredFieldBo<E> scheduleRequiredFieldBo = new ScheduleRequiredFieldBo<>();

    @Override
    public final void cacheSelf(BaseScheduleJob self) {
        super.cacheSelf(self);
        if (self instanceof IPagePoScheduleHandler) {
            @SuppressWarnings("unchecked")
            IPagePoScheduleHandler<E> pagePoScheduleHandler = (IPagePoScheduleHandler<E>) self;
            this.scheduleRequiredFieldBo.setPagePoScheduleHandler(pagePoScheduleHandler);
        } else {
            log.error("can't find page po schedule handler.");
            throw new CheckedException(SystemErrorCode.SYSTEM_NOT_SUPPORT_ERROR);
        }
    }

    protected final ScheduleRequiredFieldBo<E> getScheduleRequiredFieldBo() {
        return this.scheduleRequiredFieldBo;
    }

    @Autowired(required = true)
    private void setMapper(BaseMapper<E> mapper) {
        this.scheduleRequiredFieldBo.setMapper(mapper);
    }

    @Override
    public void onStartUp() {
        this.scheduleRequiredFieldBo.setFrameworkCoreConfigProperties(ProxyUtil.getProxied(FrameworkCoreConfigProperties.class));
        this.scheduleRequiredFieldBo.setSystemFrameworkModuleService(ProxyUtil.getProxied(ISystemFrameworkModuleService.class));
        this.scheduleRequiredFieldBo.setCommonCacheService(ProxyUtil.getProxied(ICommonCacheService.class));
    }

    /**
     * @inheritDoc
     */

    @Override
    public Response<String> handle(String params) {
        this.scheduleRequiredFieldBo.setParams(params);
        long dataCount = ScheduleHelper.systemVersionPageSchedule(scheduleRequiredFieldBo);
        log.info("process data count {}, page size {}", dataCount, getPageSize(params));
        return Response.success(String.valueOf(dataCount));
    }
}
